package com.xingshang.controller;

import cn.hutool.core.bean.BeanUtil;
import com.xingshang.model.po.User;
import com.xingshang.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    @GetMapping("/login")
    public String login(Model model, HttpSession session) {
        System.out.println("登陆页面");
        model.addAttribute("site", "星殇商城");
        if(session.getAttribute("user")!=null){
            return "redirect:/";
        }
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String account, @RequestParam String password, HttpSession session) {
        User user = userService.login(account, password);

        System.out.println(user);
        if (BeanUtil.isNotEmpty(user)) {
            session.setAttribute("user", user);
            System.out.println("密码正确");
            return "redirect:/";
        } else {
            System.out.println("密码错误");
            return "redirect:/user/login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/";
    }

    @GetMapping("/register")
    public String register(Model model) {
        System.out.println("注册页面");
        model.addAttribute("site", "星殇商城");
        return "register";
    }



    @PostMapping("/register")
    @ResponseBody
    public String register(@RequestParam String account,
                           @RequestParam String password,
                           @RequestParam String email,
                           @RequestParam String telphone,
                           @RequestPart MultipartFile avatar,
                           Model model
    ) throws IOException {

        int i = userService.insertUser(account, password, email, telphone,avatar);
        if (i > 0) {
            System.out.println("注册成功");
            model.addAttribute("msg", "注册成功");
            return "success";
        }
        model.addAttribute("msg", "注册失败");
        return "fail";
    }
}
